package com.lottery.ruok.lottrey.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.lottery.ruok.lottrey.R;
import com.lottery.ruok.lottrey.adapter.MyPagerAdapter;
import com.lottery.ruok.lottrey.adapter.SummaryAdapter;
import com.lottery.ruok.lottrey.adapter.SummaryTypeAdapter;
import com.lottery.ruok.lottrey.eventbusObject.OrderFilter;
import com.lottery.ruok.lottrey.retrofitModule.RetrofitBase;
import com.lottery.ruok.lottrey.retrofitModule.RxHelper;
import com.lottery.ruok.lottrey.retrofitModule.RxSubscribe;
import com.lottery.ruok.lottrey.retrofitModule.request.MemberSummaryRequest;
import com.lottery.ruok.lottrey.retrofitModule.response.MemberSummaryResponse;
import com.lottery.ruok.lottrey.userInfo.UserInfo;
import com.lottery.ruok.lottrey.utils.TimeUtil;

import org.greenrobot.eventbus.EventBus;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.TimeZone;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import ui.NoScrollViewPager;

/*
 * 汇总时间选择页面
 * */

public class SummaryActivity extends BaseActivity {


    @BindView(R.id.today)
    TextView today;
    @BindView(R.id.yesterday)
    TextView yesterday;
    @BindView(R.id.this_week)
    TextView thisWeek;
    @BindView(R.id.last_week)
    TextView lastWeek;
    @BindView(R.id.start_time)
    TextView startTime;
    @BindView(R.id.end_time)
    TextView endTime;
    @BindView(R.id.viewPager)
    NoScrollViewPager viewPager;
    @BindView(R.id.close)
    ImageView close;
    @BindView(R.id.confirm)
    TextView confirm;


    ArrayList<View> mViewList = new ArrayList<>();
    private ListView listView1;
    private ListView listView2;
    private String mStartTime;
    private String mEndTime;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_summary);

        ButterKnife.bind(this);

        init();
    }

    private void init() {
        String START = "起始时间";
        startTime.setHint(START);
        String END = "截止时间";
        endTime.setHint(END);

        View view1 = getLayoutInflater().inflate(R.layout.filter_summary1, null);
        view1.findViewById(R.id.switch1).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //if(mStartTime != null && mEndTime != null && !mStartTime.equals(mEndTime)) {
                if(mStartTime != null && mEndTime != null ) {
                    getSubList(null, mStartTime, mEndTime, "1");
                    viewPager.setCurrentItem(1, true);
                }
            }
        });
        View view2 = getLayoutInflater().inflate(R.layout.filter_summary2, null);
        view2.findViewById(R.id.switch1).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                viewPager.setCurrentItem(0, true);
            }
        });

        mViewList.add(view1);
        mViewList.add(view2);

        MyPagerAdapter myPagerAdapter = new MyPagerAdapter(mViewList);
        viewPager.setAdapter(myPagerAdapter);

        listView1 = mViewList.get(0).findViewById(R.id.listview);
        listView2 = mViewList.get(1).findViewById(R.id.listview);

        Date d = new Date(System.currentTimeMillis());
        SimpleDateFormat sp= new SimpleDateFormat("yyyy-MM-dd");
        sp.setTimeZone(TimeZone.getTimeZone("UTC"));
        String today = sp.format(d);
        getList(null, today, today);

    }

    private void getSubList(final String day, final String start, final String end, final String is_all){
        RetrofitBase.getRetrofit().create(MemberSummaryRequest.class).getResult(UserInfo.getToken(), day, start, end, is_all)
                .compose(RxHelper.<MemberSummaryResponse>handleResult())
                .subscribe(new RxSubscribe<MemberSummaryResponse>(this) {
                    @Override
                    protected void _onNext(final MemberSummaryResponse memberSummaryResponse) {
                        listView2.setAdapter(new SummaryTypeAdapter(memberSummaryResponse, SummaryActivity.this));
                        listView2.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                            @Override
                            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                                if(day == null) {
                                    OrderFilter orderFilter = new OrderFilter();
                                    if (memberSummaryResponse.getList().get(i).getName().equals("全部")) {
                                        orderFilter.setCode(null);
                                    } else {
                                        orderFilter.setCode(memberSummaryResponse.getList().get(i).getLayout_code());
                                    }
                                    orderFilter.setStart(start);
                                    orderFilter.setEnd(end);
                                    EventBus.getDefault().post(orderFilter);
                                } else {
                                    OrderFilter orderFilter = new OrderFilter();
                                    if (memberSummaryResponse.getList().get(i).getName().equals("全部")) {
                                        orderFilter.setCode(null);
                                    } else {
                                        orderFilter.setCode(memberSummaryResponse.getList().get(i).getLayout_code());
                                    }
                                    orderFilter.setStart(day + " 00:00:00");
                                    orderFilter.setEnd(day + " 23:59:59");
                                    EventBus.getDefault().post(orderFilter);
                                }

                                finish();
                            }
                        });
                    }

                    @Override
                    protected boolean showDialog() {
                        return false;
                    }
                });
    }

    private void getList(final String day, final String start, final String end) {
        RetrofitBase.getRetrofit().create(MemberSummaryRequest.class).getResult(UserInfo.getToken(), day, start, end, null)
                .compose(RxHelper.<MemberSummaryResponse>handleResult())
                .subscribe(new RxSubscribe<MemberSummaryResponse>(this) {
                    @Override
                    protected void _onNext(final MemberSummaryResponse memberSummaryResponse) {
                        if(start != null && end != null){
                            mStartTime = start;
                            mEndTime = end;
                        } else {
                            mStartTime = null;
                            mEndTime = null;
                        }
                        listView1.setAdapter(new SummaryAdapter(memberSummaryResponse, SummaryActivity.this));
                        listView1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                            @Override
                            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                                if(memberSummaryResponse.getList().get(i).getName().equals("全部")){
                                    if(start != null && end != null){//范围
                                        if(start.equals(end)){
                                            getSubList(null, start + " 00:00:00", end + " 23:59:59", "1");
                                        } else {
                                            getSubList(null, start, end, "1");
                                        }
                                        viewPager.setCurrentItem(1, true);
                                    } else {
                                        OrderFilter orderFilter = new OrderFilter();
                                        orderFilter.setCode(null);
                                        orderFilter.setStart(day + " 00:00:00");
                                        orderFilter.setEnd(day + " 23:59:59");
                                        EventBus.getDefault().post(orderFilter);
                                        finish();
                                    }
                                } else {
                                    if(memberSummaryResponse.getIs_lottery() == 1){
                                        OrderFilter orderFilter = new OrderFilter();
                                        orderFilter.setCode(memberSummaryResponse.getList().get(i).getLayout_code());
                                        if(day != null){
                                            orderFilter.setStart(day + " 00:00:00");
                                            orderFilter.setEnd(day + " 23:59:59");
                                        } else {
                                            if(start != null && end != null && start.equals(end)){
                                                orderFilter.setStart(start + " 00:00:00");
                                                orderFilter.setEnd(start + " 23:59:59");
                                            }
                                        }
                                        EventBus.getDefault().post(orderFilter);
                                        finish();
                                    } else {
                                        getSubList(memberSummaryResponse.getList().get(i).getName(), null, null, null);
                                        viewPager.setCurrentItem(1, true);
                                    }
                                }
                            }
                        });
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    protected boolean showDialog() {
                        return false;
                    }
                });
    }

    @OnClick({R.id.today, R.id.yesterday, R.id.this_week, R.id.last_week, R.id.start_time, R.id.end_time, R.id.close, R.id.confirm})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.today:
//                chooseIndex = 0;

                today.setBackgroundResource(R.drawable.bg_corners_100_3);
                yesterday.setBackgroundResource(R.drawable.bg_corners_100_12);
                thisWeek.setBackgroundResource(R.drawable.bg_corners_100_12);
                lastWeek.setBackgroundResource(R.drawable.bg_corners_100_12);

                today.setTextColor(Color.parseColor("#ffffff"));
                yesterday.setTextColor(Color.parseColor("#3f3f3f"));
                thisWeek.setTextColor(Color.parseColor("#3f3f3f"));
                lastWeek.setTextColor(Color.parseColor("#3f3f3f"));

                startTime.setText("");
                endTime.setText("");

                setConfirmCondition();

                startTime.setBackgroundResource(R.drawable.bg_corners_24);
                endTime.setBackgroundResource(R.drawable.bg_corners_24);

                Date d = new Date(System.currentTimeMillis());
                SimpleDateFormat sp= new SimpleDateFormat("yyyy-MM-dd");
                sp.setTimeZone(TimeZone.getTimeZone("UTC"));
                String ZUOTIAN = sp.format(d);
                viewPager.setCurrentItem(0, false);

                getList(null, ZUOTIAN, ZUOTIAN);
                break;
            case R.id.yesterday:
//                chooseIndex = 1;

                today.setBackgroundResource(R.drawable.bg_corners_100_12);
                yesterday.setBackgroundResource(R.drawable.bg_corners_100_3);
                thisWeek.setBackgroundResource(R.drawable.bg_corners_100_12);
                lastWeek.setBackgroundResource(R.drawable.bg_corners_100_12);

                today.setTextColor(Color.parseColor("#3f3f3f"));
                yesterday.setTextColor(Color.parseColor("#ffffff"));
                thisWeek.setTextColor(Color.parseColor("#3f3f3f"));
                lastWeek.setTextColor(Color.parseColor("#3f3f3f"));

                startTime.setText("");
                endTime.setText("");

                setConfirmCondition();

                startTime.setBackgroundResource(R.drawable.bg_corners_24);
                endTime.setBackgroundResource(R.drawable.bg_corners_24);

                Date d1=new Date(System.currentTimeMillis()-1000*60*60*24);
                SimpleDateFormat sp1=new SimpleDateFormat("yyyy-MM-dd");
                sp1.setTimeZone(TimeZone.getTimeZone("UTC"));
                String ZUOTIAN1 = sp1.format(d1);

                viewPager.setCurrentItem(0, false);

                getList(null, ZUOTIAN1, ZUOTIAN1);
                break;
            case R.id.this_week:
//                chooseIndex = 2;

                today.setBackgroundResource(R.drawable.bg_corners_100_12);
                yesterday.setBackgroundResource(R.drawable.bg_corners_100_12);
                thisWeek.setBackgroundResource(R.drawable.bg_corners_100_3);
                lastWeek.setBackgroundResource(R.drawable.bg_corners_100_12);

                today.setTextColor(Color.parseColor("#3f3f3f"));
                yesterday.setTextColor(Color.parseColor("#3f3f3f"));
                thisWeek.setTextColor(Color.parseColor("#ffffff"));
                lastWeek.setTextColor(Color.parseColor("#3f3f3f"));

                startTime.setText("");
                endTime.setText("");

                setConfirmCondition();

                startTime.setBackgroundResource(R.drawable.bg_corners_24);
                endTime.setBackgroundResource(R.drawable.bg_corners_24);

              /*  Calendar cal = Calendar.getInstance();
                Calendar first = (Calendar) cal.clone();
                first.add(Calendar.DAY_OF_WEEK, first.getFirstDayOfWeek() - first.get(Calendar.DAY_OF_WEEK) + 1);
                Calendar last = (Calendar) first.clone();
                last.add(Calendar.DAY_OF_YEAR, 6);
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
                df.setTimeZone(TimeZone.getTimeZone("UTC"));*/

                viewPager.setCurrentItem(0, false);
                Map<String,String> map = new HashMap<>();
                map.putAll(TimeUtil.getWeekDate());
                getList(null, map.get("mondayDate"),  map.get("sundayDate"));
                break;
            case R.id.last_week:
//                chooseIndex = 3;

                today.setBackgroundResource(R.drawable.bg_corners_100_12);
                yesterday.setBackgroundResource(R.drawable.bg_corners_100_12);
                thisWeek.setBackgroundResource(R.drawable.bg_corners_100_12);
                lastWeek.setBackgroundResource(R.drawable.bg_corners_100_3);

                today.setTextColor(Color.parseColor("#3f3f3f"));
                yesterday.setTextColor(Color.parseColor("#3f3f3f"));
                thisWeek.setTextColor(Color.parseColor("#3f3f3f"));
                lastWeek.setTextColor(Color.parseColor("#ffffff"));

                startTime.setText("");
                endTime.setText("");

                setConfirmCondition();

                startTime.setBackgroundResource(R.drawable.bg_corners_24);
                endTime.setBackgroundResource(R.drawable.bg_corners_24);

               /* Calendar cal1 = Calendar.getInstance();
                Calendar first1 = (Calendar) cal1.clone();
                first1.add(Calendar.DAY_OF_WEEK, first1.getFirstDayOfWeek() - first1.get(Calendar.DAY_OF_WEEK) - 6);
                Calendar last1 = (Calendar) first1.clone();
                last1.add(Calendar.DAY_OF_YEAR, 6);
                SimpleDateFormat df1 = new SimpleDateFormat("yyyy-MM-dd");
                df1.setTimeZone(TimeZone.getTimeZone("UTC"));*/

                viewPager.setCurrentItem(0, false);
                Map<String,String> map2 = new HashMap<>();
                map2.putAll(TimeUtil.getLastWeekDate());

                getList(null,  map2.get("mondayDate"),  map2.get("sundayDate"));
                break;
            case R.id.start_time:
                Intent intent = new Intent(SummaryActivity.this, ChooseDateActivity.class);
                if(!endTime.getText().toString().equals("")){
                    intent.putExtra("endTime", endTime.getText().toString() + " 00:00:00");
                }
                if(!startTime.getText().toString().equals("")){
                    intent.putExtra("time", startTime.getText().toString() + " 00:00:00");
                }
                startActivityForResult(intent, 101);
                overridePendingTransition(R.anim.anim_enter_from_bottom, R.anim.activity_stay);
                break;
            case R.id.end_time:
                Intent intent1 = new Intent(SummaryActivity.this, ChooseDateActivity.class);
                if(!startTime.getText().toString().equals("")){
                    intent1.putExtra("startTime", startTime.getText().toString() + " 00:00:00");
                }
                if(!endTime.getText().toString().equals("")){
                    intent1.putExtra("time", endTime.getText().toString() + " 00:00:00");
                }
                startActivityForResult(intent1, 102);
                overridePendingTransition(R.anim.anim_enter_from_bottom, R.anim.activity_stay);
                break;
            case R.id.close:
                finish();
                break;
            case R.id.confirm:
                viewPager.setCurrentItem(0, false);

                getList(null, startTime.getText().toString(), endTime.getText().toString());
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == 101 && resultCode == Activity.RESULT_OK) {
            startTime.setText(data.getStringExtra("date").split(" ")[0]);
            startTime.setBackgroundResource(R.drawable.bg_corners_14);

            setConfirmCondition();

            today.setTextColor(Color.parseColor("#3f3f3f"));
            yesterday.setTextColor(Color.parseColor("#3f3f3f"));
            thisWeek.setTextColor(Color.parseColor("#3f3f3f"));
            lastWeek.setTextColor(Color.parseColor("#3f3f3f"));

            today.setBackgroundResource(R.drawable.bg_corners_100_12);
            yesterday.setBackgroundResource(R.drawable.bg_corners_100_12);
            thisWeek.setBackgroundResource(R.drawable.bg_corners_100_12);
            lastWeek.setBackgroundResource(R.drawable.bg_corners_100_12);
        } else if (requestCode == 102 && resultCode == Activity.RESULT_OK) {
            endTime.setText(data.getStringExtra("date").split(" ")[0]);
            endTime.setBackgroundResource(R.drawable.bg_corners_14);

            setConfirmCondition();

            today.setTextColor(Color.parseColor("#3f3f3f"));
            yesterday.setTextColor(Color.parseColor("#3f3f3f"));
            thisWeek.setTextColor(Color.parseColor("#3f3f3f"));
            lastWeek.setTextColor(Color.parseColor("#3f3f3f"));

            today.setBackgroundResource(R.drawable.bg_corners_100_12);
            yesterday.setBackgroundResource(R.drawable.bg_corners_100_12);
            thisWeek.setBackgroundResource(R.drawable.bg_corners_100_12);
            lastWeek.setBackgroundResource(R.drawable.bg_corners_100_12);
        }
    }

    private void setConfirmCondition(){
        if(!endTime.getText().equals("") && !startTime.getText().equals("")){
            confirm.setVisibility(View.VISIBLE);
        } else {
            confirm.setVisibility(View.GONE);
        }
    }

    @Override
    public void finish() {
        super.finish();

        overridePendingTransition(0, R.anim.anim_exit_from_bottom);
    }
}
